﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PowerCreator.LMS.Course.Entity;
using PowerCreator.LMS.Common.Utils;
using PowerCreator.LMS.Web.Course;
using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Web.Config;
using System.IO;

public partial class Theme_DL_OpenCourseware : PowerCreator.LMS.Web.Base.WebBasePage
{
    //更新学习资源，如果没有的参数，则使用0替换,1添加资源访问记录
    protected string _isUpdateCourse = "0";
    protected string _Position = "0";

    string _openhistoryurl = "OpenHistory.aspx?ProjectID={0}&ProjectClassID={1}&ProjectClassUserID={2}&ProjectResourceID={3}&CourseResourceID={4}&ResourceID={5}&ProjectResourceResourceStartTime={6}";

    protected string _url = "";  //更新课件访问信息URL
    protected string _fileUrl = "";

    protected string _vPowerCreator = "0";   //是否调PowerCreator课件界面,1调用，其它为不调用

    PowerCreator.LMS.Web.Course.Course opCourse = new PowerCreator.LMS.Web.Course.Course();                     //课程管理
    protected PowerCreator.LMS.Web.Config.WebConfig config = new PowerCreator.LMS.Web.Config.WebConfig();

    PowerCreator.LMS.Web.Course.VirtualDirectory opVirtual = new VirtualDirectory();
    PowerCreator.LMS.Web.Course.Resource opResource = new Resource();
    private PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
    private string url = "UserLogin.aspx";

    protected void Page_Load(object sender, EventArgs e)
    {
        //CheckUser();
        if (!IsPostBack)
        {
            this.Title = config.GetLanagerValueByKey("theme_Comment_TitleInfo", PowerCreator.LMS.Language.LanagetItemType.Page);

            BinderUserLogin();
            btn_out.Text = config.GetLanagerValueByKey("SignOut", PowerCreator.LMS.Language.LanagetItemType.WebTitle);

            //InitPage();
            ViewState["ClassID"] = "0";
            ViewState["CourseID"] = "0";
            ViewState["CourseResourceID"] = "0";
            ViewState["ResourceID"] = "0";
           // ViewState["CourseResourceID"] = "0";
            ViewState["UserID"] = "0";

            string resourceid = Request.QueryString["ResourceID"].ToString();
            ViewState["ResourceID"] = resourceid;

            string CourseResourceID = Request.QueryString["CourseResourceID"].ToString();
            ViewState["CourseResourceID"] = CourseResourceID;
            string courseID = Request.QueryString["CourseID"].ToString();
            ViewState["CourseID"] = courseID;
            if (Request.QueryString["ClassID"] != null)
            {
                string classID = Request.QueryString["ClassID"].ToString();
                ViewState["ClassID"] = classID;
            }
            _Position = Request.QueryString["Position"].ToString();


            BinderPage();
        }
    }



    private void CheckUser()
    {
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {
            Script.RedirectURL(url);
        }

        login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
        if (login == null)
        {
            Script.RedirectURL(url);
        }
        //else
        //{
        //    验证此课件该用户是否可以点播
        //    PowerCreator.LMS.Web.User.LoginEntity login = (PowerCreator.LMS.Web.User.LoginEntity)Session[WebConfig.SESSION_USER_USERINFO];
        //    string courseIDlist = getMyCourseIDlist();
        //}


    }


    protected void lnkbtn_EN_Click(object sender, EventArgs e)
    {
        Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_LANGEID] = "1";
    }
    protected void lnkbtn_CN_Click(object sender, EventArgs e)
    {
        Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_LANGEID] = "0";
    }
    protected void BinderUserLogin()
    {
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {
            lal_UserLogin.Text = "<a  href=\"UserLogin.aspx\">" + config.GetLanagerValueByKey("SysManagerLogin", PowerCreator.LMS.Language.LanagetItemType.Page) + "</a> |  <a  href=\"Register.aspx\">" + config.GetLanagerValueByKey("SysManagerRegistor", PowerCreator.LMS.Language.LanagetItemType.Page) + "</a>";
            btn_out.Visible = false;
        }
        else
        {
            PowerCreator.LMS.Web.DL.User.LoginEntity login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            lal_UserLogin.Text = login.RealName + "," + config.GetLanagerValueByKey("Login_msg_code5", PowerCreator.LMS.Language.LanagetItemType.Page) + "！| ";
            btn_out.Visible = true;
        }
    }
    protected void btn_out_Click(object sender, EventArgs e)
    {
        //opUser.UpdateOnlineUserByUserID(GetLoginEntity.UserID);
        Session.Abandon();
        PowerCreator.LMS.Common.Script.Script.ReloadMe();
    }


    //private string getMyCourseIDlist()
    //{
    //    sbSearch.Append(string.Format(" and CourseID in (select FKUCCourseID from UserCourse where UCUserID={0} ) ", login.UserID));
    //}
    private void BinderPage()
    {
        VOTResource vo = opCourse.LoadResource(int.Parse(ViewState["ResourceID"].ToString()));
        if (vo != null)
        {
            vo.ResourceClickNum += 1;
            vo.ResourceLastVisitTime = DateTime.Now;
            if (!opCourse.UpdateResource(vo))
            {
                lab_err.Text = config.GetLanagerValueByKey("theme_PageCode_ErrmMsg", PowerCreator.LMS.Language.LanagetItemType.Page);
            }
        }



        _fileUrl = "../Single/content.aspx?rsd=" + ViewState["ResourceID"];
       

        if (vo.ResourceClass == Convert.ToInt16(SysResourceType.PowerCreator))
        {
            //检查课件是否是第一次被点播，如果是第一次被点播，则修改remoteclip.asx文件。
            if (!vo.ResourceMmsUpdateState)
            {
                PowerCreator.LMS.Web.Course.Resource opResource = new Resource();
                opResource.UpdataResourceByEditMMS(vo);
            }


            if (PowerCreator.LMS.Web.Config.WebConfig.IsUseWeGe)
            {
                CheckUser();
                PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
                login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
                _fileUrl ="OpenCourseWareCommentNew.aspx?ProjectID=0&ClassID=0&UserID=" + login.UserID.ToString() + "&ProjectResourceID=0&CoursResourceID=" + ViewState["CourseResourceID"].ToString() + "&ResourceID=" + vo.ResourceID.ToString() + "&Position=0&CourseID=" + ViewState["CourseID"];
                Script.RedirectURL(_fileUrl);
            }

            _vPowerCreator = "1";
            pl_PowerCreaotr.Visible = true;
            // pl_coursewarecomment.Visible = true;
            pl_Video.Visible = false;
            pl_Download.Visible = false;
        }
        else if (vo.ResourceClass == Convert.ToInt16(SysResourceType.Video))
        {
            if (PowerCreator.LMS.Web.Config.WebConfig.IsUseWeGe)
            {
                CheckUser();
                _fileUrl = "OpenCourseWareCommentNew.aspx?ProjectID=0&ClassID=0&UserID=" + login.UserID.ToString() + "&ProjectResourceID=0&CoursResourceID=" + ViewState["CourseResourceID"].ToString() + "&ResourceID=" + vo.ResourceID.ToString() + "&CourseID=" + ViewState["CourseID"] + "&Position=0";
                Script.RedirectURL(_fileUrl);
                _vPowerCreator = "1";
                pl_PowerCreaotr.Visible = true;
                // pl_coursewarecomment.Visible = true;
                pl_Video.Visible = false;
                pl_Download.Visible = false;
                SetOpenHistoryUrl();
                return;

            }
            else
            {
                //PowerCreator.LMS.ViewQuery.ViewQuery opView = new PowerCreator.LMS.ViewQuery.ViewQuery();
                //string sDirName = opResource.GetDirctoryName(vo.ResourceUrl);
                //string search = "select VirId,VirIisName,VirMmsName,VirIp from TVirtualDirectory where VirIisName='" + sDirName + " '";
                //DataTable dt = opView.Query(search);
                //if (dt.Rows.Count == 1)
                //{
                //    string ServerIP;
                //    if (PowerCreator.LMS.Web.Config.WebConfig.IsUseURLIP)
                //    {
                //        int index = Request.Url.Authority.IndexOf(":", 0);
                //        if (index != -1)
                //        {
                //            ServerIP = Request.Url.Authority.Remove(index);
                //        }
                //        else
                //        {
                //            ServerIP = Request.Url.Authority;
                //        }

                //        _fileUrl = "mms://" + ServerIP + vo.ResourceUrl + vo.ResourceEntry;
                //    }
                //    else
                //    {
                //        ServerIP = dt.Rows[0]["VirIp"].ToString();
                //        string sResourceMMSUrl = vo.ResourceUrl.Replace(sDirName, dt.Rows[0]["VirMmsName"].ToString());
                //        _fileUrl = "mms://" + ServerIP + sResourceMMSUrl + vo.ResourceEntry;
                //    }
                //}
                _fileUrl = "../Video/OpenVideo.aspx?rsd=" + ViewState["ResourceID"];

            }
            _vPowerCreator = "0";
            pl_PowerCreaotr.Visible = false;
            pl_Video.Visible = true;
            pl_Download.Visible = false;
            //pl_coursewarecomment.Visible = false;
        }
        else if (vo.ResourceClass == Convert.ToInt16(SysResourceType.Download))
        {
            _vPowerCreator = "0";
            //绑定界面数据
            lbl_CreatedTime.Text = vo.ResourceCreatedTime.ToString("yyyy/MM/dd");
            lbl_DownloadCount.Text = vo.ResourceClickNum.ToString();
            lbl_LastTime.Text = vo.ResourceLastVisitTime.ToString("yyyy/MM/dd");
            lbl_ResourceName.Text = vo.ResourceName;
            //li_Description.Text = vo.ResourceDescription;

            if (!string.IsNullOrEmpty(vo.ResourceEntry))
            {
                string fileExtension = string.Empty;
                string url = vo.ResourceEntry;
                string[] urls = url.Split('.');
                if (url.Length > 1)
                    fileExtension = urls[urls.Length - 1];

                lbl_image.Text  = "<img src=\"images/File/" + fileExtension + ".jpg\" width=\"88\" height=\"88\" />";
            }
            else
            {
                lbl_image.Text = "<img src=\"../1/images/GauntEagleGem.gif\" width=\"88\" height=\"88\" />";
            }



            //hyplnk_FileUrl.NavigateUrl = _fileUrl;
            hyplnk_ImgFileurl.NavigateUrl = _fileUrl;
            //hyplnk_ImgFileurl.Target = "_";
            pl_PowerCreaotr.Visible = false;
            pl_Video.Visible = false;
            //pl_coursewarecomment.Visible = false;
            pl_Download.Visible = true;
        }
        else if (vo.ResourceClass == Convert.ToInt16(SysResourceType.NoPowerCreator))
        {
            _vPowerCreator = "1";
            pl_PowerCreaotr.Visible = true;
            //pl_coursewarecomment.Visible = false;
            pl_Video.Visible = false;
            pl_Download.Visible = false;
        }
        else if (vo.ResourceClass == Convert.ToInt16(SysResourceType.WebCourseware))
        {
            _vPowerCreator = "1";
            pl_PowerCreaotr.Visible = true;
            //pl_coursewarecomment.Visible = true;
            pl_Video.Visible = false;
            pl_Download.Visible = false;
        }

        SetOpenHistoryUrl();

       
    }
    private void SetOpenHistoryUrl()
    {
        PowerCreator.LMS.Web.DL.User.LoginEntity login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
        if (login != null)
        {
            ViewState["UserID"] = login.UserID;
            _isUpdateCourse = "1";
            _openhistoryurl = WebUtils.WebRoot + "/web/Project/" + _openhistoryurl;
            _url = string.Format(_openhistoryurl, ViewState["ClassID"].ToString(), ViewState["ClassID"].ToString(), ViewState["UserID"].ToString(), ViewState["CourseID"].ToString(), ViewState["CourseResourceID"].ToString(), ViewState["ResourceID"].ToString(), DateTime.Now.ToString());

        }  
    }
    //protected override void InitPage()
    //{
    //    base.InitPage();
    //}

    protected void imgbtn_FileDown_Click(object sender, ImageClickEventArgs e)
    {
        VOTResource vo = opCourse.LoadResource(int.Parse(ViewState["ResourceID"].ToString()));

        _fileUrl = WebUtils.WebRoot + vo.ResourceUrl + vo.ResourceEntry;
        string path = Server.MapPath(_fileUrl);

        if (System.IO.File.Exists(path))
        {
            try
            {
                //打开要下载的文件
                System.IO.FileStream r = new System.IO.FileStream(path, System.IO.FileMode.Open);
                //设置基本信息

                Response.Buffer = false;
                Response.AddHeader("Connection", "Keep-Alive");
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(path));
                Response.AddHeader("Content-Length", r.Length.ToString());

                while (true)
                {
                    //开辟缓冲区空间
                    byte[] buffer = new byte[1024];
                    //读取文件的数据
                    int leng = r.Read(buffer, 0, 1024);
                    if (leng == 0)//到文件尾，结束
                        break;
                    if (leng == 1024)//读出的文件数据长度等于缓冲区长度，直接将缓冲区数据写入
                        Response.BinaryWrite(buffer);
                    else
                    {
                        //读出文件数据比缓冲区小，重新定义缓冲区大小，只用于读取文件的最后一个数据块
                        byte[] b = new byte[leng];
                        for (int i = 0; i < leng; i++)
                            b[i] = buffer[i];
                        Response.BinaryWrite(b);
                    }
                }
                r.Close();//关闭下载文件
                Response.End();//结束文件下载
            }
            catch (Exception ex)
            {
                // BaseWriteLog(ex.Message);
                lab_err.Text = config.GetLanagerValueByKey("theme_Course_DownLoadErrMsg", PowerCreator.LMS.Language.LanagetItemType.Page) + ex.Message;
            }
           
            vo.ResourceClickNum += 1;
            vo.ResourceLastVisitTime = DateTime.Now;
            if (!opCourse.UpdateResource(vo))
            {
                lab_err.Text = config.GetLanagerValueByKey("theme_PageCode_ErrmMsg", PowerCreator.LMS.Language.LanagetItemType.Page);
            }
        }
        else
        {

        }
    }



}
